package com.epalmpay.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by Administrator on 2018/5/30.
 */
public class RedisUtil {

    public static final String REDISADDRESS = "r-bp1aea358447bbc4.redis.rds.aliyuncs.com";//测试
    //public static final String REDISADDRESS = "r-bp1b68a092608a14.redis.rds.aliyuncs.com";//正式
    public static final int REDISPORT = 6379;
    public static final String REDISPASSWORD = "wYXonmKrVOCzfcn1";//测试
    //public static final String REDISPASSWORD = "PXA4EZdHU1HM2n3x";//正式
    // 连接 redis 等待时间
    public static final int timeout = 10000;
    // 可用连接实例的最大数目，默认值为8；
    public static final int maxTotal = 512;
    // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8
    public static final int maxIdle = 300;
    // 等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException
    public static final int maxWait = 10000;
    // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的
    public static final boolean testOnBorrow  = true;
    // 连接池
    private JedisPool jedisPool = null;

    public RedisUtil() {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(maxTotal);
            config.setMaxIdle(maxIdle);
            config.setMaxWaitMillis(maxWait);
            config.setTestOnBorrow(testOnBorrow);
            jedisPool = new JedisPool(config, REDISADDRESS, REDISPORT, timeout, REDISPASSWORD);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取redis链接
     * @return
     */
    public Jedis getJedis() {
        if (jedisPool != null) {
            return jedisPool.getResource();
        }
        return null;
    }

    public static void main(String[] args) {
        RedisUtil redisUtil = new RedisUtil();
        System.out.println(redisUtil.getJedis());
    }
}
